package com.ai.chat.controller;

import com.ai.chat.entity.Message;
import com.ai.chat.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/messages")
public class MessageController {

    @Autowired
    private MessageService messageService;

    /**
     * 发送消息
     */
    @PostMapping
    public ResponseEntity<Map<String, Message>> sendMessage(
            @RequestParam Long conversationId,
            @RequestParam String content,
            Authentication authentication) {
        Long userId = Long.valueOf(authentication.getName());
        Map<String, Message> messages = messageService.sendMessage(userId, conversationId, content);
        return ResponseEntity.ok(messages);
    }

    /**
     * 获取对话消息列表
     */
    @GetMapping("/conversation/{conversationId}")
    public ResponseEntity<List<Message>> getMessagesByConversationId(
            @PathVariable Long conversationId,
            Authentication authentication) {
        Long userId = Long.valueOf(authentication.getName());
        List<Message> messages = messageService.getMessagesByConversationId(conversationId, userId);
        return ResponseEntity.ok(messages);
    }

    /**
     * 删除消息
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Boolean> deleteMessage(
            @PathVariable Long id,
            Authentication authentication) {
        Long userId = Long.valueOf(authentication.getName());
        boolean deleted = messageService.deleteMessage(id, userId);
        return ResponseEntity.ok(deleted);
    }
}